import "babel-polyfill"

const path = require('path')
const cookieParser = require('cookie-parser')

const express = require('express')
const app = express()

// const history = require('connect-history-api-fallback')
// app.use('/',history())

app.all('*', function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*")
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	// res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
	res.header("X-Powered-By", ' 3.2.1')
	res.header("Content-Type", "application/json;charset=utf-8")
	next()
})

//解析JSON
//文件大小限制
const bodyParser = require('body-parser');
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }))
// 解析 application/json
app.use(bodyParser.json({ limit: '50mb' }))

//请求头
const cors = require('cors')
app.use(cors());

//解析数据
// import { dataAnalysis } from './utils/middleware.js'
// app.use(dataAnalysis)

//托管静态路径
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
// app.use(express.static(path.join(__dirname, 'public/dist')))


// 中间件
import db from './utils/dbconf'
import { SAVE_LOG } from './server.config'
app.use(async ({headers,method,url},res,next) => {
  try {
    if(SAVE_LOG){
      const action = `${method}:${url}`
      const ua = headers['user-agent']
      const { cip,cid } = JSON.parse(decode(headers['citysn']))
      await db.table('log')
        .add({action,ua,cip,cid})
    }
    const tokendata = JSON.parse(headers['token'] || '{}')
    Object.assign(res.locals,tokendata)
    next()
  } catch (error) {
    return res.send({ code:500,msg:'用户行为异常' })
  }
})

app.use('/api/adm', require('./routes/adm'))
app.use('/api/user', require('./routes/user'))

//启动服务
const http = require('http')
const server = http.createServer(app)
import { pass_one_day } from './corn/index'
import { START_PORT } from './server.config'
import { decode } from "js-base64"
server.listen(START_PORT,()=>{
  console.log(`运行成功: 127.0.0.1:${START_PORT}`)
	pass_one_day()//每天执行的任务
})